package com.hctforgreen.greenservice.ui.handler;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.DbFeedBackController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBFeedbackInfoManager;
import com.hctforgreen.greenservice.model.BaseEntity;
import com.hctforgreen.greenservice.model.FeedBackListEntity.FeedBackEntity;
import com.hctforgreen.greenservice.ui.page.AbstractDataLoaderHandler;
import com.hctforgreen.greenservice.ui.page.AbstractDataResponseHandler;
import com.hctforgreen.greenservice.ui.page.AbstractDataResult;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;

/**
 * 10、根据用户Id获取反馈信息
 * 
 * @author Tallen Zhai
 */
public class FeedBackListHandler implements
		AbstractDataLoaderHandler<BaseEntity>,
		AbstractDataResponseHandler<AbstractDataResult<BaseEntity>> {
	public final static int GET_DIALPHONE_SUCCESS = 0x1111;

	private HctController mController = null;

	private View mConvertView;

	private boolean mLoading;
	private String dialPhone;

	private ArrayList<BaseEntity> mValues = new ArrayList<BaseEntity>();

	private DataLoadedCallback<BaseEntity> mCallback;

	private int mMaxItems;

	private int pageNo;

	private String mPersonId = "";

	private boolean fromHistory;

	private Activity mActivity;

	public FeedBackListHandler(Activity activity, View convertView,
			String personId, String dialPhone, boolean fromHistory) {

		mController = new HctController(activity);
		mActivity = activity;
		mConvertView = convertView;
		mPersonId = personId;
		this.dialPhone = dialPhone;
		this.fromHistory = fromHistory;
	}

	public String getDialPhone() {
		return dialPhone;
	}

	public ArrayList<BaseEntity> getValues() {
		return mValues;
	}

	@Override
	public void resultTopAvailable(int status,
			AbstractDataResult<BaseEntity> result) {
		if (status == REQUEST_SUCCESS) {
			mValues.clear();
			mCallback.clear();
			mLoading = false;

			if (mMaxItems == 0)
				mMaxItems = result.maxItems;
			if (result.values == null) {
				mCallback.showLoading(false);
				return;
			}
			if (result.values.size() == 0) {
				mMaxItems = mValues.size();
				mCallback.showLoading(false);
				return;
			}
			mValues.addAll(result.values);
			mCallback.refreshTop(result.values);
		} else if (status == REQUEST_FAILED) {
			mCallback.refreshTop(null);
		}
	}

	@Override
	public void resultAvailable(int status,
			AbstractDataResult<BaseEntity> result) {
		if (status == REQUEST_SUCCESS) {
			mLoading = false;
			if (mMaxItems == 0)
				mMaxItems = result.maxItems;
			if (result.values == null) {
				mCallback.showLoading(false);
				return;
			}
			if (result.values.size() == 0) {
				mMaxItems = mValues.size();
				mCallback.showLoading(false);
				return;
			}
			mValues.addAll(result.values);
			mCallback.dataLoaded(result.values);
		} else if (status == REQUEST_FIRST_SUCCESS) {

			if (mMaxItems < 1) {

				mLoading = false;

				mCallback.showLoading(false);

				mConvertView.findViewById(R.id.lyt_default_list_load)
						.setVisibility(View.GONE);
				mConvertView.findViewById(R.id.lyt_default_list_reload)
						.setVisibility(View.GONE);
				mConvertView.findViewById(R.id.lst_default_list).setVisibility(
						View.GONE);
				mConvertView.findViewById(R.id.lyt_default_list_empty)
						.setVisibility(View.VISIBLE);
			} else {
				mConvertView.findViewById(R.id.lyt_default_list_load)
						.setVisibility(View.GONE);
				mConvertView.findViewById(R.id.lst_default_list).setVisibility(
						View.VISIBLE);
				mConvertView.findViewById(R.id.lyt_default_list_empty)
						.setVisibility(View.GONE);
				mConvertView.findViewById(R.id.lyt_default_list_reload)
						.setVisibility(View.GONE);
				mLoading = false;
				if (mMaxItems == 0)
					mMaxItems = result.maxItems;
				if (result.values.size() == 0) {
					mMaxItems = mValues.size();
					mCallback.showLoading(false);
					return;
				}
				mValues.addAll(result.values);
				mCallback.dataLoaded(result.values);

			}
		} else if (status == REQUEST_FIRST_FAILED) {
			mConvertView.findViewById(R.id.lyt_default_list_load)
					.setVisibility(View.GONE);
			/**
			 * 重新加载layout
			 */
			final View reloadView = mConvertView
					.findViewById(R.id.lyt_default_list_reload);
			reloadView.setVisibility(View.VISIBLE);
			// reloadView.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			// mConvertView.findViewById(R.id.lyt_default_list_load)
			// .setVisibility(View.VISIBLE);
			// reloadView.setVisibility(View.GONE);
			// new FirstBackgroundTask(NewsLstHandler.this)
			// .execute();
			// }
			// });

			Button btnReload = (Button) reloadView
					.findViewById(R.id.btn_default_list_reload);

			btnReload.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mConvertView.findViewById(R.id.lyt_default_list_load)
							.setVisibility(View.VISIBLE);
					reloadView.setVisibility(View.GONE);
					new FirstBackgroundTask(FeedBackListHandler.this).execute();
				}
			});
		} else if (status == REQUEST_FAILED) {
			mCallback.showLoading(false);
			mCallback.showReloading(true);
			View reloadingView = mCallback.getReloadingView();
			Button btnReload = (Button) reloadingView
					.findViewById(R.id.btn_reloading);
			btnReload.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mCallback.showLoading(true);
					mCallback.showReloading(false);
					new BackgroundTask(FeedBackListHandler.this)
							.execute(mValues.size());
				}
			});
		}
	}

	@Override
	public int getMaxItems() {
		return mMaxItems;
	}

	@Override
	public void getValues(DataLoadedCallback<BaseEntity> callback) {
		if (mValues.isEmpty()) {
			if (mConvertView.findViewById(R.id.lyt_default_list_load) != null) {
				mConvertView.findViewById(R.id.lyt_default_list_load)
						.setVisibility(View.VISIBLE);
			}
			if (mConvertView.findViewById(R.id.lyt_default_list_empty) != null) {
				mConvertView.findViewById(R.id.lyt_default_list_empty)
						.setVisibility(View.GONE);
			}

			// No data has been loaded before.
			// Load the initial data which includes the max size.
			// mLoading = true;
			mCallback = callback;
			new FirstBackgroundTask(this).execute();
		} else {
			callback.dataLoaded(mValues);
		}
	}

	@Override
	public void getNext(DataLoadedCallback<BaseEntity> callback) {
		if (mValues.size() < mMaxItems && mValues.size() != 0) {

			mCallback.showLoading(true);
			mLoading = true;
			mCallback = callback;
			new BackgroundTask(this).execute(mValues.size());
		}
	}

	@Override
	public boolean isLoading() {
		return mLoading;
	}

	public void refersh() {
		mValues.clear();
		mCallback.clear();

		mConvertView.findViewById(R.id.lyt_default_list_load).setVisibility(
				View.VISIBLE);
		mConvertView.findViewById(R.id.lyt_default_list_empty).setVisibility(
				View.GONE);
		mConvertView.findViewById(R.id.lyt_default_list_reload).setVisibility(
				View.GONE);
		mCallback.showLoading(false);
		new FirstBackgroundTask(FeedBackListHandler.this).execute();
	}

	public void refreshTop(long timestamp) {
		new TopBackgroundTask(FeedBackListHandler.this)
				.execute(/* timestamp */);
	}

	/**
	 * 顶部下拉刷新
	 * 
	 * @author Tallen Zhai
	 * 
	 */
	private class TopBackgroundTask extends
			AsyncTask<Long, Void, AbstractDataResult<BaseEntity>> {
		private AbstractDataResponseHandler<AbstractDataResult<BaseEntity>> mResponseHandler;

		private TopBackgroundTask(
				AbstractDataResponseHandler<AbstractDataResult<BaseEntity>> responseHandler) {
			mResponseHandler = responseHandler;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected AbstractDataResult<BaseEntity> doInBackground(Long... params) {

			try {
				pageNo = FIRST_PAGENO;
				HctResult ret = new HctResult();

				ret = mController.getFeedBackJsonByPersonId(mPersonId,
						String.valueOf(pageNo));

				if (ret.status == HctConstants.STATUS_SUCCESS) {
					dialPhone = ret.phone;
					mMaxItems = ret.totalSize;

					ArrayList<BaseEntity> values = (ArrayList<BaseEntity>) ret.data;
					AbstractDataResult<BaseEntity> result = new AbstractDataResult<BaseEntity>();
					result.maxItems = mMaxItems;
					result.values = values;

					return result;
				} else {
					return null;
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(AbstractDataResult<BaseEntity> result) {
			if (result == null) {
				mResponseHandler.resultTopAvailable(REQUEST_FAILED, result);
			} else {
				mResponseHandler.resultTopAvailable(REQUEST_SUCCESS, result);
			}
		}

	}

	/**
	 * 第一次底部刷新
	 * 
	 * @author Tallen Zhai
	 */
	private class FirstBackgroundTask extends
			AsyncTask<Void, Void, AbstractDataResult<BaseEntity>> {
		private AbstractDataResponseHandler<AbstractDataResult<BaseEntity>> mResponseHandler;

		private FirstBackgroundTask(
				AbstractDataResponseHandler<AbstractDataResult<BaseEntity>> responseHandler) {
			mResponseHandler = responseHandler;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected AbstractDataResult<BaseEntity> doInBackground(Void... params) {
			if (fromHistory) {
				return getHistoryFeedBackListResult();
			} else {
				try {
					pageNo = FIRST_PAGENO;
					HctResult ret = new HctResult();

					ret = mController.getFeedBackJsonByPersonId(mPersonId,
							String.valueOf(pageNo));

					if (ret.status == HctConstants.STATUS_SUCCESS) {
						dialPhone = ret.phone;
						mMaxItems = ret.totalSize;

						ArrayList<BaseEntity> values = (ArrayList<BaseEntity>) ret.data;
						AbstractDataResult<BaseEntity> result = new AbstractDataResult<BaseEntity>();
						result.maxItems = mMaxItems;

						result.values = values;

						return result;
					} else {
						return getDbFeedBackListResult();
					}
				} catch (Exception ex) {
					ex.printStackTrace();
					return getDbFeedBackListResult();
				}
			}
		}

		private AbstractDataResult<BaseEntity> getDbFeedBackListResult() {
			DbFeedBackController dbFeedBackController = new DbFeedBackController(
					mActivity);
			List<FeedBackEntity> reData = dbFeedBackController
					.getFeedBackEntityLst();

			HctResult ret = new HctResult();
			ret.data = reData;
			ret.totalSize = reData.size();

			ArrayList<BaseEntity> values = (ArrayList<BaseEntity>) ret.data;
			AbstractDataResult<BaseEntity> result = new AbstractDataResult<BaseEntity>();
			if (reData != null && reData.size() > 0) {
				mMaxItems = ret.totalSize;

				result.maxItems = mMaxItems;
				result.values = values;
				return result;
			} else {

				return null;
			}
		}

		private AbstractDataResult<BaseEntity> getHistoryFeedBackListResult() {
			DBFeedbackInfoManager dbFeedBackController = new DBFeedbackInfoManager(
					mActivity);
			List<FeedBackEntity> reData = dbFeedBackController.queryAll();

			HctResult ret = new HctResult();
			ret.data = reData;
			ret.totalSize = reData.size();

			ArrayList<BaseEntity> values = (ArrayList<BaseEntity>) ret.data;
			AbstractDataResult<BaseEntity> result = new AbstractDataResult<BaseEntity>();
			if (reData != null && reData.size() > 0) {
				mMaxItems = ret.totalSize;

				result.maxItems = mMaxItems;
				result.values = values;
				return result;
			} else {

				return null;
			}
		}

		@Override
		protected void onPostExecute(AbstractDataResult<BaseEntity> result) {
			if (result == null) {
				mResponseHandler.resultAvailable(REQUEST_FIRST_FAILED, result);
			} else {
				mResponseHandler.resultAvailable(REQUEST_FIRST_SUCCESS, result);
			}
		}

	}

	/**
	 * 底部刷新
	 * 
	 * @author Tallen Zhai
	 */
	private class BackgroundTask extends
			AsyncTask<Integer, Void, AbstractDataResult<BaseEntity>> {
		private AbstractDataResponseHandler<AbstractDataResult<BaseEntity>> mResponseHandler;

		private BackgroundTask(
				AbstractDataResponseHandler<AbstractDataResult<BaseEntity>> responseHandler) {
			mResponseHandler = responseHandler;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected AbstractDataResult<BaseEntity> doInBackground(
				Integer... params) {
			try {
				pageNo++;
				HctResult ret = new HctResult();

				ret = mController.getFeedBackJsonByPersonId(mPersonId,
						String.valueOf(pageNo));

				if (ret.status == HctConstants.STATUS_SUCCESS) {
					dialPhone = ret.phone;
					ArrayList<BaseEntity> values = (ArrayList<BaseEntity>) ret.data;
					AbstractDataResult<BaseEntity> result = new AbstractDataResult<BaseEntity>();

					if (ret.totalSize < Integer.MAX_VALUE) {
						mMaxItems = ret.totalSize;
					}
					// Since this is loaded the first time, the max item should
					// be
					// made
					// available.
					result.maxItems = mMaxItems;
					result.values = values;

					return result;
				} else {
					return null;
				}

			} catch (Exception ex) {
				ex.printStackTrace();
				return null;
			}

		}

		@Override
		protected void onPostExecute(AbstractDataResult<BaseEntity> result) {
			if (result == null) {
				mResponseHandler.resultAvailable(REQUEST_FAILED, result);
			} else {
				mResponseHandler.resultAvailable(REQUEST_SUCCESS, result);
			}
		}
	}
}
